package com.zeusee.main.lpr.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.zeusee.main.lpr.R;
import com.zeusee.main.lpr.bean.PlateInfo;
import com.zeusee.main.lpr.jni.PlateRecognition;

import java.util.Iterator;
import java.util.List;


public class ImageActivity extends Activity implements View.OnClickListener {
    private static final int REQUEST_CODE_IMAGE_CAMERA = 1;
    private static final int REQUEST_CODE_IMAGE_OP = 2;
    private static final int REQUEST_CODE_OP = 3;
    private final String TAG = getClass().toString();
    public Button btn;
    public ImageView imgv;
    boolean istracking = false;
    private Uri mPath;
    public TextView resbox;
    public String result = "";
    public TextView runtimebox;
    public SeekBar sb;

    private String getPath(Uri uri) {
        Uri uri2 = null;
        if (Build.VERSION.SDK_INT < 19 || !DocumentsContract.isDocumentUri(this, uri)) {
            Cursor managedQuery = managedQuery(uri, new String[]{"_data"}, (String) null, (String[]) null, (String) null);
            int columnIndexOrThrow = managedQuery.getColumnIndexOrThrow("_data");
            managedQuery.moveToFirst();
            String string = managedQuery.getString(columnIndexOrThrow);
            String substring = string.substring(string.length() - 4);
            if (substring.compareToIgnoreCase(".jpg") == 0 || substring.compareToIgnoreCase(".png") == 0) {
                return string;
            }
            return null;
        }
        String[] split = DocumentsContract.getDocumentId(uri).split(":");
        String str = split[0];
        if ("image".equals(str)) {
            uri2 = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if ("video".equals(str)) {
            Uri uri3 = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            return null;
        } else if ("audio".equals(str)) {
            Uri uri4 = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            return null;
        }
        return getDataColumn(this, uri2, "_id=?", new String[]{split[1]});
    }


    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    public static Bitmap decodeImage(String str) {
        try {
            int attributeInt = new ExifInterface(str).getAttributeInt("Orientation", 1);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            options.inJustDecodeBounds = false;
            Bitmap decodeFile = BitmapFactory.decodeFile(str, options);
            Matrix matrix = new Matrix();
            if (attributeInt == 6) {
                matrix.postRotate(90.0f);
            } else if (attributeInt == 3) {
                matrix.postRotate(180.0f);
            } else if (attributeInt == 8) {
                matrix.postRotate(270.0f);
            }
            Bitmap createBitmap = Bitmap.createBitmap(decodeFile, 0, 0, decodeFile.getWidth(), decodeFile.getHeight(), matrix, true);
            Log.d("com.arcsoft", "check target Image:" + createBitmap.getWidth() + "X" + createBitmap.getHeight());
            if (!createBitmap.equals(decodeFile)) {
                decodeFile.recycle();
            }
            return createBitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == REQUEST_CODE_IMAGE_OP && resultCode == RESULT_OK) {
            this.mPath = intent.getData();
            final String path = getPath(this.mPath);
            System.currentTimeMillis();
            this.imgv.setImageBitmap(getBItmapByPath(path));
            this.result = "识别中";
            this.resbox.setText(this.result);
            new Thread(new Runnable() {
                public void run() {
                    ImageActivity.this.istracking = true;
                    final List<PlateInfo> plateRecognitionByPath = PlateRecognition.getInstance().plateRecognitionByPath(path, 40, 500, 1);
                    Iterator<PlateInfo> it = plateRecognitionByPath.iterator();
                    while (it.hasNext()) {
                        if (((double) it.next().getConfidence()) < 0.85d) {
                            it.remove();
                        }
                    }
                    ImageActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            ImageActivity.this.istracking = false;
                            if (plateRecognitionByPath.size() > 0) {
                                ImageActivity imageActivity = ImageActivity.this;
                                String unused = imageActivity.result = ImageActivity.this.result + "车牌号:" + ((PlateInfo) plateRecognitionByPath.get(0)).getPlateName() + "\n";
                                ImageActivity imageActivity2 = ImageActivity.this;
                                String unused2 = imageActivity2.result = ImageActivity.this.result + "置信度:" + String.valueOf(((PlateInfo) plateRecognitionByPath.get(0)).getConfidence()) + "\n";
                                ImageActivity imageActivity3 = ImageActivity.this;
                                String unused3 = imageActivity3.result = ImageActivity.this.result + "车牌颜色:" + ((PlateInfo) plateRecognitionByPath.get(0)).color[((PlateInfo) plateRecognitionByPath.get(0)).getPlateType()] + "\n";
                                ImageActivity.this.resbox.setText(ImageActivity.this.result);
                            } else {
                                String unused4 = ImageActivity.this.result = "没有识别结果";
                                ImageActivity.this.resbox.setText(ImageActivity.this.result);
                            }
//                            Intent intent = new Intent(ImageActivity.this, ResultActivity.class);
//                            intent.putExtra("result", (Serializable) plateRecognitionByPath);
//                            ImageActivity.this.startActivity(intent);
                            if (plateRecognitionByPath.get(0) != null) {
                                PlateInfo plateInfo = plateRecognitionByPath.get(0);
                                Toast.makeText(ImageActivity.this, "结果：" + plateInfo.getPlateName(), Toast.LENGTH_SHORT).show();

                            }
                        }
                    });
                }
            }).start();
        } else if (requestCode == REQUEST_CODE_OP) {
            String str = this.TAG;
            Log.i(str, "RESULT =" + resultCode);
            if (intent != null) {
                String string = intent.getExtras().getString("imagePath");
                String str2 = this.TAG;
                Log.i(str2, "path=" + string);
            }
        } else if (requestCode == REQUEST_CODE_IMAGE_CAMERA && resultCode == RESULT_OK) {
            decodeImage(getPath(this.mPath));
        }
    }

    private Bitmap getBItmapByPath(String str) {
        Bitmap decodeFile = BitmapFactory.decodeFile(str);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int i = displayMetrics.widthPixels;
        if (decodeFile.getWidth() <= i) {
            return decodeFile;
        }
        return Bitmap.createScaledBitmap(decodeFile, i, (decodeFile.getHeight() * i) / decodeFile.getWidth(), true);
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_image);
        if (ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE") != 0) {
            ActivityCompat.requestPermissions(this, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 123);
        }
        this.btn = (Button) findViewById(R.id.button);
        this.imgv = (ImageView) findViewById(R.id.imageView);
        this.resbox = (TextView) findViewById(R.id.textView);
        this.sb = (SeekBar) findViewById(R.id.seek);
        this.runtimebox = (TextView) findViewById(R.id.textView3);
        this.btn.setOnClickListener(this);
    }

    public void onClick(View view) {
        if (view.getId() == R.id.button) {
            if (this.istracking) {
                Toast.makeText(this, "识别中，请稍后", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent("android.intent.action.GET_CONTENT");
            intent.addCategory("android.intent.category.OPENABLE");
            intent.setType("image/jpeg");
            startActivityForResult(intent, REQUEST_CODE_IMAGE_OP);
        }
    }
}
